var fs = require('fs');
var template = fs.readFileSync('test/test.html').toString();
var cheerio = require('cheerio');
var $ = cheerio.load(template);
var dataCombine = require('../src/data-combine');

require('./combineConfig')(dataCombine);

var exampleList = $('#exampleList');

var JSDOM = require('jsdom').JSDOM;

//测试DOM中
var list = exampleList.find('li');
list.each(function (i) {
	if (i >= list.length - 1) {//最后一项用于开发，去掉自动化测试
		return;
	}
	var item = $(this);
	var itemDom = JSDOM.fragment(item.html());

	var combineDoms = itemDom.querySelectorAll('.to-combine');

	//测试data-combine start
	let testData = dataCombine({
		target: combineDoms[0]
	});
	let targetData = str2obj(itemDom.querySelector('target').textContent.trim());
	let targetDataStr = JSON.stringify(targetData, null, 2);

	//生成的值与预计的值一样
	var isWrong = JSON.stringify(testData, null, 2) !== targetDataStr;
	console.log(i, targetData);

	isWrong && (console.log(testData) || testError(item, i, 0));

	isWrong = !judgeChain(testData);

	isWrong && (console.log(testData) || testError(item, i, 1));
	//测试data-combine end
});

function judgeChain(obj, isDebug) {//判断combine关系是否正确
	if (isDebug) {
		debugger
	}
	for (var attr in obj) {
		if (obj.hasOwnProperty(attr)) {
			var sonObj = obj[attr];
			if (typeof sonObj === 'object' && sonObj != null) {
				var com = sonObj.__combine__;
				if (typeof com === 'string') {
					console.log(com);
				} else if (com.parent !== obj || !judgeChain(sonObj)) {
					return false;
				}
			}
		}
	}
	return true;
}

function testError(target, i, status) {
	var zh = {
		0: 'same',
		1: 'chain',
	};
	throw Error(zh[status] + ' : (' + i + ') ' + target.find('h4').text().trim() + ' 判断错误！！！');
}

console.log('all is RIGHT');

function str2obj(str) {
	return new Function('return ' + str)();
}



